//
//  FGNetWork.swift
//  FlagApp
//
//  Created by momo on 2020/12/30.
//

import Moya
import HandyJSON
import SVProgressHUD
let LoadingPlugin = NetworkActivityPlugin { (type, target) in
//    guard let vc = UIViewController() else { return }
//    switch type {
//    case .began:
//        break
//    case .ended:
//        break
//    }
}

let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider<UApi>.RequestResultClosure) -> Void in
    if var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 20
        closure(.success(urlRequest))
    } else {
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

let ApiProvider = MoyaProvider<UApi>(requestClosure: timeoutClosure)
let ApiLoadingProvider = MoyaProvider<UApi>(requestClosure: timeoutClosure, plugins: [LoadingPlugin])


enum UApi {
    case login(login_tel: String, password: String)//登录
}

extension UApi: TargetType {
    private struct UApiKey {
        static var key = "api"  //key
        static var channelID = "aitask_plus" //渠道号
        static var headMd5Str = ""   //md5加密之后的字符串
        static var keyChannelID = "\(UApiKey.channelID)\(UApiKey.key)"
    }
    var baseURL: URL { return URL(string: "http://aitask.jtarw.com/")! }
    
    var path: String {
        switch self {
        case .login: return "checkLogin"
       
        }
    }
    
    var task: Task {
        var parmeters : Dictionary<String,Any> = [:]
        let userid:String?
        let token:String?
        parmeters = ["user_id":"","token":""]
        switch self {
        case .login(let login_tel, let password):
            parmeters["login_tel"] = login_tel
            parmeters["password"] = password
        
        
         default: break
        }
        
        let str = "\(UApiKey.keyChannelID)\(parmeters.dicToUrl(signParmeters: parmeters))"
        let sign = str.MMD5().MMD5()
        print("签名之后的东西",sign)
        UApiKey.headMd5Str =  sign.uppercased()
        print(parmeters.formatJSON()!,"上传的参数")
        parmeters["device"] = "ios"
        if ((path.urlDecode?.description .hasSuffix(""))!) {
             return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
        }
         return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
      
       
    }
    
    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    var parameterEncoding: ParameterEncoding {
        return JSONEncoding.default
    }
    
    var headers: [String: String]? {
        return nil

//     return   [
//                 "device_id": UIDevice.current.identifierForVendor!.uuidString,
//                 "model": UIDevice.current.modelName,
//                 "version": Bundle.main.infoDictionary!["CFBundleShortVersionString"]! as! String]

    }

    
    var method: Moya.Method {
        if (((path.urlDecode?.description .hasSuffix(""))) != nil) {
           return .get
        }
        return .post
    }
}

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) throws -> T {
        let jsonString = String(data: data, encoding: .utf8)
        print(jsonString as Any)
        guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) else {
            throw MoyaError.jsonMapping(self)
        }
        print(model as Any,T.self as Any)
        return model
    }
}

extension MoyaProvider {
    @discardableResult
    open func request<T: HandyJSON>(_ target: Target,
                                    model: T.Type,
                                    completion: ((_ returnData: T? , _ msg:String , _ code:Int) -> Void)?) -> Cancellable? {
        
        return request(target, completion: { (result) in

            guard let completion = completion else {
                 return
            }
            guard let returnData = try? result.value?.mapModel(ResponseData<T>.self) else {
                completion(nil, "", 999)
                 return
            }
            if (returnData.code == 0){
                return
            }
            
            if(returnData.code == 300){
                 return
            }
            
            if(returnData.code == 200){
                 return
            }
              
            completion(returnData.data, returnData.msg ?? "", returnData.code)
        })
    }
}

